import {
    Button,
    Divider, Form, Input, InputNumber, message, Popconfirm, Select,
    Space,
    Table, Tag,

    Typography
} from 'antd';
import {useEffect, useState} from "react";
import {post} from "../../../Util/AxiosUtil";
import {useNavigate} from "react-router-dom";
import axios from "axios";
import {ProxyConfigClass} from "../../../Util/Proxy";
import Cookies from "js-cookie";
import {v4 as uuid} from "uuid";



const App = () => {
    const navigate = useNavigate();
    const [count, setCount] = useState(2);
    const [selectionType, setSelectionType] = useState('checkbox');
    const [page, setPage] = useState(0);
    const [size, setSize] = useState(2);
    const [users, setUsers] = useState([])
    const [editingKey, setEditingKey] = useState('');
    const [form] = Form.useForm();
    const [tag,setTag]=useState([])
    useEffect(()=>{
        axios.post(ProxyConfigClass.isProxy ? ProxyConfigClass.urlPrefix : ProxyConfigClass.isGoLongUrt +"/userManage/roles" , {}, {
            headers: {
                "Token": Cookies.get("Token")
            }
        }).then(function (response) {
            const res=response.data
            if (res.msg === "账号再其他地方登录请重新登录") {
                message.warning("账号再其他地方登录请重新登录")
                navigate("/hello")
            }else{
                message.success(res.msg)
                console.log(res)
                setTag(res.roles.map(t=>{
                   return ({
                       value:    t.Id,
                       label: t.Description
                   })}))
                console.log(res.roles.map(t=>{
                        return {value:    t.Id,
                            label: t.Description
                        }
                    }
                ))
                console.log(tag)
                console.log("--------------")
            }
        }).catch(function (error) {

        });
    },[])
    const handleChange = (value) => {
        console.log(`Selected: ${value}`);
    };
    const EditableCell = ({
                              editing,
                              dataIndex,
                              title,
                              inputType,
                              record,
                              index,
                              children,
                              ...restProps
                          }) => {
        const inputNode = inputType === 'tags' ?   <Select
            mode="multiple"
            size={size}
            placeholder="Please select"
            defaultValue={[]}
            onChange={handleChange}
            style={{
                width: '100%',
            }}
            options={tag}
        /> : <Input/>;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    const isEditing = (record) => record.key === editingKey;
    const edit = (record) => {
        form.setFieldsValue({
            name: '',
            age: '',
            address: '',
            ...record,
        });
        setEditingKey(record.key);
    };
    const cancel = () => {
        setEditingKey('');
    };
    const save = async (key) => {
        console.log(key)
        try {
            const row = await form.validateFields();
            const newData = [...users];
            const index = newData.findIndex((item) => key === item.key);
            if (index > -1) {
                const item = newData[index];
                console.log(tag)
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                row.tag=row.tags.toString()
                row.key=key
                console.log(row)
                console.log("+++++++++++++++++")
                setUsers(newData);
                axios.post(ProxyConfigClass.isProxy ? ProxyConfigClass.urlPrefix : ProxyConfigClass.isGoLongUrt +"/userManage/update" , {
                    "data":{
                        ...row,
                    }
                }, {
                    headers: {
                        "Token": Cookies.get("Token")
                    }
                }).then(function (response) {
                    const res=response.data
                    if (res.msg === "账号再其他地方登录请重新登录") {
                        message.warning("账号再其他地方登录请重新登录")
                        navigate("/hello")
                    }else{
                        message.success(res.msg)
                    }
                }).catch(function (error) {

                });
                console.log({
                    ...item,
                    ...row,
                })
                setEditingKey('');
            } else {
                newData.push(row);
                setUsers(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const handleDelete = (key) => {
        axios.post(ProxyConfigClass.isProxy ? ProxyConfigClass.urlPrefix : ProxyConfigClass.isGoLongUrt +"/userManage/delect" , {
            "data":{
                Id:key
            }
        }, {
            headers: {
                "Token": Cookies.get("Token")
            }
        }).then(function (response) {
            const res=response.data
            if (res.msg === "账号再其他地方登录请重新登录") {
                message.warning("账号再其他地方登录请重新登录")
                navigate("/hello")
            }else {
                message.success(res.msg)
            }
        }).catch(function (error) {
            alert(error);
        });
        const newData = users.filter((item) => item.key !== key);
        setUsers(newData);
    };
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            name: record.name,
        }),
    };

    const selectUser = () => {
        // var ressss = post("/userManage/select/"+page+"/"+size,{},{
        //     headers: {
        //         "Token": "1ba61ef7-d733-4d10-b146-450a18ceca0c"
        //     }
        // });
        // console.log(ressss)


               // .users.map(t => {
               //      return {
               //          "key": t.Id,
               //          "Id": t.Id,
               //          "Username": t.Username,
               //          "Password": t.Password
               //
               //      }
               //  })
        axios.post(ProxyConfigClass.isProxy ? ProxyConfigClass.urlPrefix : ProxyConfigClass.isGoLongUrt +"/userManage/select/"+page+"/"+size , {}, {
            headers: {
                "Token": Cookies.get("Token")
            }
        }).then(function (response) {
            const res=response.data
            if (res.msg === "账号再其他地方登录请重新登录") {
                message.warning("账号再其他地方登录请重新登录")
                navigate("/hello")
                return
            }else {
                message.success(res.msg)
            }
            console.log(response.data)
            setUsers(response.data.users.map(t => {
                return {
                    "key": t.Id,
                    "Id": t.Id,
                    "Username": t.Username,
                    "Password": t.Password,
                    "tags":t.Roles.map(
                        t=>{
                         return({  value:    t.Id,
                             label: t.Description
                         })
                        }
                    )

                }
            }))
        }).catch(function (error) {

        });
    }
    const columns = [
        {
            title: 'Id',
            dataIndex: 'Id',
            key: 'Id',
        },
        {
            title: '账号',
            dataIndex: 'Username',
            key: 'Username',
            editable: true,
        }, {
            title: '密码',
            dataIndex: 'Password',
            key: 'Password',
            editable: true,
        },
        {
            title: '删除',
            dataIndex: 'delete',
            render: (_, record) =>
                users.length >= 1 ? (
                    <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.key)}>
                        <a>删除</a>
                    </Popconfirm>
                ) : null,
        },
        {
            title: '修改',
            dataIndex: 'chage',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
            <Typography.Link
                onClick={() => save(record.key)}
                style={{
                    marginRight: 8,
                }}
            >
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        修改
                    </Typography.Link>
                );
            }
        }, {
            title: 'Tags',
            key: 'tags',
            dataIndex: 'tags',
            editable: true,

            render: (tags) => (
                <span>
        <Select
            disabled
            mode="multiple"
            size={size}
            placeholder="Please select"
            defaultValue={tags}
            onChange={handleChange}
            style={{
                width: '100%',
            }}
            options={tag}
        />
      </span>
            ),
        },
    ]
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                inputType: col.dataIndex === 'tags' ? 'tags' : 'text',
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    const handleAdd = () => {
        var uuId = uuid();
        const newData = {
            key:uuId,
            Id: uuId,
            Username: "userName",
            Password: "Password",
        };
        setUsers([...users, newData]);
    };
    return (
        <>
            <Button type="primary" onClick={() => selectUser()}>
                查询
            </Button>
           第 <InputNumber onChange={(number)=>{
            setPage(number)
        }}/>几页
            每页查询<InputNumber onChange={(number)=>{
            setSize(number)
        }} />条
            <Divider/>
            <Form form={form} component={false}>
                <Button
                    onClick={handleAdd}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    Add a row
                </Button>
                <Table
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                    columns={mergedColumns}
                    dataSource={users}
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    rowClassName="editable-row"
                    pagination={{
                        onChange: cancel,
                    }
                }
                />
            </Form>

        </>
    );
};
export default App;
